package com.example.alwaysrun;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.widget.Toast;

public class RunService extends Service {

	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 接收广播：设备上新安装了一个应用程序包后自动启动新安装应用程序。
			if (intent.getAction()
					.equals("android.intent.action.PACKAGE_ADDED")) {
				String packageName = intent.getDataString().substring(8);
				System.out.println("---------------" + packageName);
				Toast.makeText(context, packageName, 0).show();
				Intent intent2 = new Intent(); 
			 	PackageManager packageManager = context.getPackageManager(); 
			 	intent2 = packageManager.getLaunchIntentForPackage(packageName); 
			 	intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP) ; 
			 	context.startActivity(intent2);
			}
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		registerInstallMonitor();
	}
	

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		unregisterInstalMonitor();
		super.onDestroy();
		// startService(new Intent("com.alwaysrun"));
	}
	
	private void registerInstallMonitor(){
		IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        registerReceiver(receiver, filter);
	}
	
	private void unregisterInstalMonitor(){
		try{
			unregisterReceiver(receiver);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
